package com_github_lib_base.base

import android.annotation.SuppressLint
import android.graphics.Color
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebSettings.LOAD_NO_CACHE
import android.webkit.WebView
import android.widget.RelativeLayout
import androidx.core.view.isVisible
import androidx.databinding.ViewDataBinding
import com.github.lib_base.R
import com.github.lib_base.databinding.ActivityBaseWebBinding
import com.just.agentweb.AgentWeb
import com.just.agentweb.DefaultWebClient
import com.just.agentweb.WebChromeClient
import com.just.agentweb.WebViewClient

abstract class BaseWebActivity<VDB : ViewDataBinding,VM:BaseViewModel> : BaseVMActivity<VDB, VM>() {
    protected var mAgentWeb: AgentWeb? = null
    protected lateinit var mUrl: String

    // 核心初始化方法（子类必须实现）
    abstract fun provideUrl(): String


    override fun initBeforeContent() {
        hookWebView()
    }

    override fun initView() {
        mUrl = provideUrl() // 由子类决定URL
        initWebView()
    }

    @SuppressLint("MissingPermission")
    protected open fun initWebView() {
        mAgentWeb = AgentWeb.with(this)
            .setAgentWebParent((mBind as ActivityBaseWebBinding).llContainer, RelativeLayout.LayoutParams(-1, -1))
            .useDefaultIndicator()
            .setWebChromeClient(createWebChromeClient())
            .setWebViewClient(createWebViewClient())
            .setMainFrameErrorView(R.layout.layout_net_error, -1)
            .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
            .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK)
            .createAgentWeb()
            .ready()
            .go(mUrl)

        configureWebSettings(mAgentWeb?.agentWebSettings?.webSettings)
    }

    // 可重写的WebView配置方法
    protected open fun configureWebSettings(settings: WebSettings?) {
        settings?.apply {
            useWideViewPort = true
            loadWithOverviewMode = true
            cacheMode = LOAD_NO_CACHE
            mAgentWeb?.webCreator?.webView?.isFocusable = true
            mAgentWeb?.webCreator?.webView?.isFocusableInTouchMode = true
            mAgentWeb?.webCreator?.webView?.setBackgroundColor(Color.parseColor("#1A2C3E"))
        }
    }

    // 可自定义的WebClient
    protected open fun createWebChromeClient(): WebChromeClient = object : WebChromeClient() {
        override fun onReceivedTitle(view: WebView, title: String?) {
            super.onReceivedTitle(view, title)
            // 默认空实现，子类可扩展
        }
    }

    protected open fun createWebViewClient(): WebViewClient = object : WebViewClient() {
        override fun onReceivedError(
            view: WebView?,
            request: WebResourceRequest?,
            error: WebResourceError?
        ) {

        }
    }

    protected open fun handleWebError() {
        runOnUiThread { (mBind as ActivityBaseWebBinding).rlNoData.isVisible = true }
    }
}